const { get, post } = require('../common/ajax');
const { MARKET_COUPON_STATUS, MARKET_ISSUER, MARKET_DISTRIBUTE_SCENE, MARKET_SCENE } = require('../constants/market');
const { MARKET_URL } = require('../constants/url');
const { dealAvalibleCouponItem, dealAvalibleCouponList, dealCouponList } = require('../biztools/market');
const { tipError, tipSuccess } = require('../common/platform');

/**
 * 获取会员卡折扣信息
 * @param {Number|String} cardId 会员卡ID
 */
const getMemberCardDiscount = async (cardId) => {
    try {
        const res = await get(MARKET_URL.cardDiscount(cardId));
        return res.data.card_discount;
    } catch (err) {
        return { discount: 100 };
    }
};

/**
 * 获取优惠券列表
 */
const getCouponList = async (type) => {
    const res = await get(MARKET_URL.couponList, {
        member_coupon_status: type,
        with_item_confs: true,
    });
    return dealCouponList(res.data.rows || []);
};

/**
 * 获取优惠券总数
 */
const getCouponListCount = async () => {
    const res = await get(MARKET_URL.couponList, {
        member_coupon_status: MARKET_COUPON_STATUS.normal,
    });
    return res.data.total;
};

/**
 * 获取可领取的优惠券列表
 * @param {String|Number} storeId 门店id
 */
const getAvalibleCouponList = async (storeId) => {
    const res = await get(MARKET_URL.avaliableCouponList, {
        owner_id: storeId || 0,
        issuer: MARKET_ISSUER.emall,
        distribute_scene: MARKET_DISTRIBUTE_SCENE.public,
    });
    return dealAvalibleCouponList(res.data.rows || []);
};

/**
 * 领取优惠券
 * @param {String|Number} couponId 优惠券id
 */
const getPublicCoupon = async (couponId) => {
    const res = await post(MARKET_URL.getCoupon(couponId), {
        got_issuer: MARKET_ISSUER.emall,
        got_scene: MARKET_DISTRIBUTE_SCENE.public,
    })
    return res.success ? tipSuccess('领取成功') : tipError(res.msg);
};

/**
 * 获取扫码领劵优惠券信息
 * @param {String} couponId 优惠券id
 */
const getScanCouponInfo = async (couponId) => {
    const res = await get(MARKET_URL.getCouponInfo(couponId), {
        issuer: MARKET_ISSUER.emall,
        distribute_scene: MARKET_DISTRIBUTE_SCENE.qrcode,
    });
    return {
        couponInfo: dealAvalibleCouponItem(res.coupon),
        available: res.available,
    };
};

/**
 * 扫码领券
 * @param {String} couponId 优惠券id 
 */
const getScanCoupon = async (couponId) => {
    const res = await post(MARKET_URL.getCoupon(couponId), {
        got_issuer: MARKET_ISSUER.emall,
        got_scene: MARKET_DISTRIBUTE_SCENE.qrcode,
    });
    console.log('---- 扫码领劵结果', res);
    return res.success ? true : false;
};

module.exports = {
    getMemberCardDiscount,
    getCouponList,
    getCouponListCount,
    getAvalibleCouponList,
    getPublicCoupon,
    getScanCouponInfo,
    getScanCoupon,
};